package com.cy.cy2025.box

import android.view.View
import androidx.lifecycle.MutableLiveData
import java.security.MessageDigest


/**
 * 扩展方法
 */
object Box {


    /**
     * 防暴力点击事件
     */
    const val TIME_INTERVAL = 500
    fun View.setOnClickListenerByTimeInterval(
        timeInterval: Int = TIME_INTERVAL,
        onClickListener: View.OnClickListener
    ) {
        var lastClickTime = 0L
        this.setOnClickListener {
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastClickTime >= timeInterval) {
                lastClickTime = currentTime
                onClickListener.onClick(this)
            }
        }
    }


    /**
     * 只触发一次事件，触发后清空数据
     */
    fun <T> MutableLiveData<T>.once(t: T) {
        value = t
        value = null
    }

    /**
     * 字符串转MD5
     */
    fun String.md5(uppercase: Boolean = false): String {
        val bytes = MessageDigest.getInstance("MD5").digest(this.toByteArray())
        return bytes.joinToString("") {
            String.format((if (uppercase) "%02X" else "%02x"), it)
        }
    }

}